package com.paradox.aggregation.provider.config.dataSource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DynamicDatasourceAop {
    @Pointcut("@annotation(com.paradox.aggregation.provider.config.dataSource.DataSource)")
    public void dataSource(){}

    @Around("dataSource()")
    public Object aroundAdvice(ProceedingJoinPoint pjp){
        try {
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            Method method = signature.getMethod();
            DataSource annotation = method.getAnnotation(DataSource.class);
            DataSourceSwitcher.setLookupKey(annotation.value());
            Object obj=pjp.proceed();
            DataSourceSwitcher.resetLookupKey();
            return obj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }
}
